package com.yzd.learnjava.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;

public class TextFile extends ArrayList<String>{
	public static String read(String fileName) throws IOException {
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(new File(fileName).getAbsoluteFile()));
			String s ;
			while((s = reader.readLine()) != null) {
				builder.append(s);
				builder.append("\n");
			}
		} finally {
			if(reader != null) {
				reader.close();
			}
		}
		return builder.toString();
	}
	
	public static void write(String fileName, String text) throws IOException {
		try {
			PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile());
			out.print(text);
			out.close();
		} finally {}
	}
	
	public TextFile(String fileName, String spliter) throws IOException {
		super(Arrays.asList(read(fileName).split(spliter)));
		if(" ".equals(get(0))) {
			remove(0);
		}
	}
	
	public TextFile(String fielname) throws IOException {
		this(fielname,"\n");
	}
	
	public void write(String fileName) throws IOException {
		try {
			PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile());
			for(String item : this) {
				out.println(item);
			}
			out.close();
		} finally {}
	}
	
	public static void main(String[] args) throws IOException {
		String file = read("D:\\src\\git\\java\\javalearn\\src\\com\\yzd\\learnjava\\util\\TextFile.java");
		write("test.txt", file);
		TextFile textFile = new TextFile("test.txt");
		textFile.write("test2.txt");
		TreeSet<String> words = new TreeSet<String>(new TextFile("D:\\src\\git\\java\\javalearn\\src\\com\\yzd\\learnjava\\util\\TextFile.java", "\\W+"));
		Print.print(words.headSet("a"));
	}
}






















